package com.apps.realtyportal;

import java.util.ArrayList;
import java.util.List;

import mapviewballoons.example.custom.CustomItemizedOverlay;
import mapviewballoons.example.custom.CustomOverlayItem;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MultipleSearching extends SherlockFragmentActivity {

	private MapFragment mMapFragment;

	private Fragment mVisible = null;
	String[] entries = new String[] { "Property Portal", "View Card",
			"Favorites", "Settings" };
	ProgressDialog pDialog;
	private EditText txtprice_searching;
	private EditText txttype_searching;
	private EditText txtlocation_searching;
	private Button btnsearch;
	private ActionBar actionbar;
	String centerAddress = "Cebu City";
	final String KEY_ADDRESS = "address";
	final String KEY_LAT = "latitude";
	final String KEY_LON = "longitude";
	final String KEY_NAME = "property_name";
	final String KEY_DESCRIPTION = "property_description";
	final String KEY_PRICE = "price";
	final String KEY_TYPE = "propertyType";
	
	//arrays
	ArrayList pname = new ArrayList();	  
	ArrayList pdescription = new ArrayList();	  
	ArrayList pprice = new ArrayList();	  
	ArrayList wsData = new ArrayList();
	ArrayList listAdd = new ArrayList();
	ArrayList listoflat = new ArrayList();	  
	ArrayList listoflon = new ArrayList();
	ArrayList arptype = new ArrayList();
	ArrayList nearpricelat = new ArrayList();
	ArrayList nearpricelon = new ArrayList();
	ArrayList paddress = new ArrayList();

	final String jsonData = 
    		"[{\"property_id\":7,\"property_name\":\"Avialon\",\"property_description\":\"two stories, three stories\",\"price\":\"210000.00\",\"latitude\":\"10.312839\",\"longitude\":\"123.894389\",\"address\":\"Ibabao, Basak Pardo, Cebu City\",\"propertyType\":\"house\"}," +
    		"{\"property_id\":8,\"property_name\":\"Spolarium\",\"property_description\":\"nice description, sample lang\",\"price\":\"310000.00\",\"latitude\":\"10.314528\",\"longitude\":\"123.896449\",\"address\":\"basak, pardo, cebu city\",\"propertyType\":\"building\"}," +
    		"{\"property_id\":9,\"property_name\":\"NorthWest\",\"property_description\":\"sample lang gain, nice description\",\"price\":\"423456.00\",\"latitude\":\"10.313599\",\"longitude\":\"123.898208\",\"address\":\"Ibabao, Basak Pardo, Cebu City\",\"propertyType\":\"subdivision\"}," +
    		"{\"property_id\":10,\"property_name\":\"Facific\",\"property_description\":\"hundred fold stories\",\"price\":\"3000000.00\",\"latitude\":\"10.312617\",\"longitude\":\"123.886428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"building\"},"+
    		"{\"property_id\":11,\"property_name\":\"NorWay\",\"property_description\":\"hundred fold stories\",\"price\":\"400000.00\",\"latitude\":\"10.314617\",\"longitude\":\"123.896428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"house\"},"+
    		"{\"property_id\":12,\"property_name\":\"EastWing\",\"property_description\":\"hundred stories\",\"price\":\"500000.00\",\"latitude\":\"10.316617\",\"longitude\":\"123.856428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"Condominium\"},"+
    		"{\"property_id\":13,\"property_name\":\"WestWing\",\"property_description\":\"hundred stories\",\"price\":\"600000.00\",\"latitude\":\"10.315617\",\"longitude\":\"123.866428\",\"address\":\"Tass, Basak Pardo, Cebu City\",\"propertyType\":\"subdivision\"},"+
    		"{\"property_id\":14,\"property_name\":\"NorthWing\",\"property_description\":\"hundred stories\",\"price\":\"601000.00\",\"latitude\":\"10.313617\",\"longitude\":\"123.876428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"house\"},"+
    		"{\"property_id\":15,\"property_name\":\"SouthWing\",\"property_description\":\"hundred stories\",\"price\":\"700000.00\",\"latitude\":\"10.315617\",\"longitude\":\"123.896428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"building\"},"+
    		"{\"property_id\":16,\"property_name\":\"Antartic\",\"property_description\":\"hundred stories\",\"price\":\"800000.00\",\"latitude\":\"10.316617\",\"longitude\":\"123.836428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"subdivision\"},"+
    		"{\"property_id\":17,\"property_name\":\"Atlantic\",\"property_description\":\"hundred stories\",\"price\":\"900000.00\",\"latitude\":\"10.317617\",\"longitude\":\"123.856428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"house\"},"+
    		"{\"property_id\":18,\"property_name\":\"Titanium\",\"property_description\":\"hundred stories\",\"price\":\"1000000.00\",\"latitude\":\"10.318617\",\"longitude\":\"123.866428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"building\"},"+
    		"{\"property_id\":19,\"property_name\":\"Colurom\",\"property_description\":\"inspired by byby\",\"price\":\"200000.00\",\"latitude\":\"10.313617\",\"longitude\":\"123.836428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"condomenium\"},"+
    		"{\"property_id\":20,\"property_name\":\"ulayan\",\"property_description\":\"cool\",\"price\":\"3000000.00\",\"latitude\":\"10.317768\",\"longitude\":\"123.885655\",\"address\":\"Tunga, Basak Pardo, Cebu City\",\"propertyType\":\"condomenium\"}]";   		
	String strpriceselected;
	String strlocationselected;
	String strtypeselected;
	double priceselected;
	double priceinterval;
	double addeddprice;
	double convertprice;
	
	List<Overlay> newmapOverlays;
	MapController controlmap;
	CustomItemizedOverlay<CustomOverlayItem> newitemizedOverlay2;
	GeoPoint gp;
	Drawable drawable;
	int minLat = Integer.MAX_VALUE;
	int minLong = Integer.MAX_VALUE;
	int maxLat = Integer.MIN_VALUE;
	int maxLong = Integer.MIN_VALUE;
	
	int lat;
	int lon;
	Spinner price, type;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.multiplesearching);
		actionbar = getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		actionbar.setDisplayShowTitleEnabled(true);
		price =  (Spinner) this.findViewById(R.id.spinner1);
		type = (Spinner) findViewById(R.id.spinner2);
		 ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, entries);
		 					  
			/**
			 * Setting dropdown items and item navigation listener for the actionbar
			 */

//			getSupportActionBar().setListNavigationCallbacks(dataAdapter,
//					navigationListener);
			((ArrayAdapter<?>) dataAdapter)
					.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
			price.setAdapter(dataAdapter);
			type.setAdapter(dataAdapter);
//		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
//				getBaseContext(), R.layout.sherlock_spinner_item, entries);
//
//		adapter.add("Property Portal");
//		adapter.add("View Card");
//		adapter.add("Favorites");
//		adapter.add("Settings");
		
		


//		txtprice_searching = (EditText) findViewById(R.id.price_search);
//		txttype_searching = (EditText) findViewById(R.id.type_search);
		txtlocation_searching = (EditText) findViewById(R.id.location_search);
		
		// We instantiate the MapView here, it's really important!
		Exchanger.mMapView = new MapView(this,"07QrqGLNNbvFFh9LUuMashT4Bukx3tMIwwfrOaA");
		newmapOverlays = Exchanger.mMapView.getOverlays();
		
		Exchanger.mMapView.setBuiltInZoomControls(true);
		controlmap = Exchanger.mMapView.getController();		
				
		
		setupFragments();
		// We manually show the list Fragment.
		showFragment(mMapFragment);
		// start here
		actionbar.setDisplayShowCustomEnabled(true);
		View actionbar_search = LayoutInflater.from(this).inflate(
				R.layout.multiple_search_custom, null);
		btnsearch = (Button) actionbar_search.findViewById(R.id.search);
		
		btnsearch.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
//				priceSearching();
//				String locationselected = txtlocation_searching.getText().toString();
//				Toast.makeText(getBaseContext(), "no locations"+locationselected, Toast.LENGTH_LONG).show();
			}
		});
		actionbar.setCustomView(actionbar_search);
	}

	/**
	 * This method does the setting up of the Fragments. It basically checks if
	 * the fragments exist and if they do, we'll hide them. If the fragments
	 * don't exist, we create them, add them to the FragmentManager and hide
	 * them.
	 */
	private void setupFragments() {
		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();

		/*
		 * If the activity is killed while in BG, it's possible that the
		 * fragment still remains in the FragmentManager, so, we don't need to
		 * add it again.
		 */
		mMapFragment = (MapFragment) getSupportFragmentManager()
				.findFragmentByTag(MapFragment.TAG);
		if (mMapFragment == null) {
			mMapFragment = new MapFragment();
			ft.add(R.id.fragment_container, mMapFragment, MapFragment.TAG);
		}
		ft.hide(mMapFragment);

		ft.commit();
	}

	/**
	 * This method shows the given Fragment and if there was another visible
	 * fragment, it gets hidden. We can just do this because we know that both
	 * the mMyListFragment and the mMapFragment were added in the Activity's
	 * onCreate, so we just create the fragments once at first and not every
	 * time. This will avoid facing some problems with the MapView.
	 * 
	 * @param fragmentIn
	 *            The fragment to show.
	 */
	private void showFragment(Fragment fragmentIn) {
		if (fragmentIn == null)
			return;

		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();
		ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);

		if (mVisible != null)
			ft.hide(mVisible);

		ft.show(fragmentIn).commit();
		mVisible = fragmentIn;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent intent = new Intent(this, HomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * This class acts as an exchanger between the Activity and the MapFragment,
	 * so if you want, you can put the MapFragment class in a separate java
	 * file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class Exchanger {
		// We will use this MapView always.
		public static MapView mMapView;
	}

	public static class MapFragment extends SherlockFragment {

		public static final String TAG = "mapFragment";

		public MapFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// The Activity created the MapView for us, so we can do some init
			// stuff.

			final ViewGroup parent = (ViewGroup) Exchanger.mMapView.getParent();
			if (parent != null)
				parent.removeView(Exchanger.mMapView);

			Exchanger.mMapView.setClickable(true);
			Exchanger.mMapView.setBuiltInZoomControls(true); // If you want.

			/*
			 * If you're getting Exceptions saying that the MapView already has
			 * a parent, uncomment the next lines of code, but I think that it
			 * won't be necessary. In other cases it was, but in this case I
			 * don't this should happen.
			 */

			return Exchanger.mMapView;
		}
	}

	
//	public void priceSearching(){
//		
//		strpriceselected = txtprice_searching.getText().toString();
//		strlocationselected = txtlocation_searching.getText().toString();
//		if(!strpriceselected.matches("")){
//		priceselected = Double.valueOf(strpriceselected.toString()).doubleValue();
//		priceinterval = Double.valueOf(100000.00).doubleValue();
//		addeddprice = priceselected + priceinterval;
//		
//		//start here searching 
//		try {
//			JSONArray array = new JSONArray(jsonData);			
//			for (int i = 0; i < array.length(); i++) {				
//				JSONObject e = array.getJSONObject(i);
//				String coListLat = e.getString(KEY_LAT);
//				String coListLon = e.getString(KEY_LON);
//				  
//				String copname = e.getString(KEY_NAME);
//				String copdescription = e.getString(KEY_DESCRIPTION);
//				String copprice = e.getString(KEY_PRICE);
//				String coptype = e.getString(KEY_TYPE);
//				String copaddress = e.getString(KEY_ADDRESS);
//				listoflat.add(coListLat);
//				listoflon.add(coListLon);
//				pname.add(copname);
//				pdescription.add(copdescription);
//				pprice.add(copprice);
//				arptype.add(coptype);
//				paddress.add(copaddress);
//				
//			}
//			
//			
//		} catch (JSONException e) {
//			Log.e("log_tag", "Error parsing data " + e.toString());
//		}
//		for(int i = 0; i<pprice.size(); i++){
//		  String nearestprice = pprice.get(i).toString().replace(",", "");
//		  		 convertprice = Double.valueOf(nearestprice).doubleValue();		  		
//		String spname = pname.get(i).toString();
//		String spdesc = pdescription.get(i).toString();		
//		String sptype = arptype.get(i).toString();
//		if(convertprice>=priceselected){
//			if(convertprice<addeddprice){
//			if(priceselected<addeddprice){									
//				String spprice = pprice.get(i).toString();
//				double dlistwlat = Double.parseDouble((String) listoflat.get(i));
//				double dlistwlon = Double.parseDouble((String) listoflon.get(i));
//				String spaddress = paddress.get(i).toString();
//				int listwlat = (int) (dlistwlat * 1E6);
//				int listwlon = (int) (dlistwlon * 1E6);
//				
//				gp = new GeoPoint(listwlat, listwlon);
//				minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
//			    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
//			    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
//			    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );	
//				if(sptype.equals("building")){
//					drawable = getResources().getDrawable(R.drawable.building2);
//				}else if(sptype.equals("house")){
//					drawable = getResources().getDrawable(R.drawable.house2);
//				}else if(sptype.equals("subdivision")){
//					drawable = getResources().getDrawable(R.drawable.subdivision2);
//				}
//														
//				  newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, HomeActivity.Exchanger.mMapView);
//				  CustomOverlayItem overlayItem3 = new CustomOverlayItem(gp, ""+spname, 
//							""+spdesc,""+spaddress,
//							"http://ia.media-imdb.com/images/M/MV5BMjAyNjk5Njk0MV5BMl5BanBnXkFtZTcwOTA4MjIyMQ@@._V1._SX40_CR0,0,40,54_.jpg");
//					newitemizedOverlay2.addOverlay(overlayItem3);
//					newmapOverlays.add(newitemizedOverlay2);
//					newitemizedOverlay2.populateNow();
//				}
//			}
//		}			
//	}	
//		controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
//		controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
//		Exchanger.mMapView.invalidate();
//		listoflat.clear();
//		listoflon.clear();
//		pname.clear();
//		pdescription.clear();
//		pprice.clear();
//		arptype.clear();
//		}
//	 	
//	  if(!strlocationselected.matches("")){
//		  new GeoCodeAddress().execute(strlocationselected);		  
//	  }	  
//	}
//	
//	
//	public void locationSearching(){
//		String selected_location = txtlocation_searching.getText().toString();		
//	}
//	
//	private class GeoCodeAddress extends AsyncTask<String, Void, List<Address>>{
//		
//		@Override
//		protected void onPreExecute() {
//			// TODO Auto-generated method stub
//			super.onPreExecute();
//			pDialog = new ProgressDialog(MultipleSearching.this);
//			pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Searching Property..."));
//			pDialog.setIndeterminate(false);
//			pDialog.setCancelable(false);
//			pDialog.show();
//		}
//		@Override
//		protected List<Address> doInBackground(String... addressname) {
//			// TODO Auto-generated method stub
//			Geocoder geocoder = new Geocoder(getBaseContext());
//			List<Address> addresses = null;
//			
//			try {
//				// Getting a maximum of 3 Address that matches the input text
//				addresses = geocoder.getFromLocationName(addressname[0], 3);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}			
//			return addresses;
//		}
//		
//		@Override
//		protected void onPostExecute(List<Address> addresses) {
//			// TODO Auto-generated method stub
//			if(pDialog!=null){
//			pDialog.dismiss();
//			}
////			runOnUiThread(new Runnable(){
////
////				public void run() {
////					// TODO Auto-generated method stub
////					
////				}
////				
////			});
//	        if(addresses==null || addresses.size()==0){
//				Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
//				
//				// Redraws the map to clear the overlays
//		        Exchanger.mMapView.invalidate();
//			}
//			for(int i=0;i<addresses.size();i++){				
//				
//				Address address = (Address) addresses.get(i);
//				lat = (int)(address.getLatitude()*1E6);
//				lon = (int)(address.getLongitude()*1E6);
//				
//				//start here getting latitude and logitude from ws compute distance
//				//new ComputeDistance().distanceFromList(lat, lon, lat2, long2)
//				
//		        // Creating an instance of GeoPoint, to display in Google Map
//		        GeoPoint p = new GeoPoint(
//		                                  (int)(address.getLatitude()*1E6),
//		                                  (int)(address.getLongitude()*1E6)
//		                                 );
//		        
//		        String addressText = String.format("%s, %s",
//	                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
//	                    address.getCountryName());
//		        
//		        // Locate the first location
//		        if(i==0)
//		        	controlmap.animateTo(p);
//		        	controlmap.setZoom(14);
//		        	
//		        
//			}
//			
//			 Toast.makeText(getBaseContext(), ""+lat+""+lon, Toast.LENGTH_LONG).show();
//			Exchanger.mMapView.invalidate();
//		}
//		}	
//	
//		public int getLatLoc(int lat){
//			return lat;
//		}
//		public int getLonLoc(int lon){
//			return lon;
//		}
		
}
